﻿@{
    Response.CacheControl = "no-cache";
    Response.AddHeader("Pragma", "no-cache");
    Response.Expires = -1;
    
    ViewBag.Title = "Входящие накладные";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style>
    .form-horizontal .controls {
      /*original: margin-left: 160px;*/
      margin-left: 120px;
    }
</style>

<header class="jumbotron subhead" id="overview">
    <h1></h1>
    <p class="lead">Входящие накладные</p>
</header>

<div class="page">

    <div class="block" id="start-page">
        <div class="form-actions">
            <a href="javascript:void(0);" class="btn" data-action="refreshInvoiceTable">
                <i class="icon-refresh"></i> Обновить</a>
            <a href="javascript:void(0);" class="btn" data-action="toggleSearchBlock">
                Настройки поиска</a>

            <div class="pull-right">
                <a href="javascript:void(0);" class="btn btn-success" data-action="downloadInvoices">
                    <i class="icon-download"></i> Загрузить отмеченные накладные</a>
            </div>
        </div>

    <div class="hide" id="invoiceSearchBlock">
        <form name="INVOICES-FILTER" class="form-horizontal well" method="post">

            <input type="hidden" name="CUSTOMER_GUID" value="" />
            <input type="hidden" name="LOCATION_GUID" value="" />

            <div class="control-group"> 
                <label class="control-label" for="CUSTOMER_NAME">Поставщик</label>
                <div class="controls row-fluid">
                    <input type="text" class="input-large" name="CUSTOMER_NAME" value="" placeholder="">
                </div> 
            </div>                                         
                        
            <div class="control-group"> 
                <label class="control-label" for="LOCATION_NAME">Склад</label>
                <div class="controls row-fluid">
                    <input type="text" class="input-large" name="LOCATION_NAME" value="" placeholder="Склад получателя" />
                </div> 
            </div>  
    
            <div class="control-group"> 
                <label class="control-label" for="DOC_DATE_START">Дата</label>
                <div class="controls">
                    <div class="input-append date" data-date="" data-date-format="dd.mm.yyyy">
                        <input type="text" class="input-small" name="DOC_DATE_START" value="" placeholder="дд.мм.гггг" />
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                    <div class="input-append date" data-date="" data-date-format="dd.mm.yyyy">
                        <input type="text" class="input-small" name="DOC_DATE_END" value="" placeholder="дд.мм.гггг" />
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                </div> 
            </div>    
 
            <div class="control-group"> 
                <label class="control-label" for="DOC_NUMBER">№</label>
                <div class="controls">
                    <input type="text" class="input-small" name="DOC_NUMBER" value="" />
                </div> 
            </div>                                 
                        
            <div class="control-group"> 
                <label class="control-label" for="IS_ALL">Обработанные</label>
                <div class="controls row-fluid">
                    <input type="checkbox" name="IS_ALL" />
                </div> 
            </div>  

        </form>
    </div>

        <div id="data-table"></div>
    </div>

    <div class="block" id="invoice-page">

        <div class="form-actions">
            <a href="javascript:void(0);" class="btn" data-action="back">
                <i class="icon-circle-arrow-left"></i> Назад</a>

            <div class="pull-right">
                <a href="javascript:void(0);" class="btn btn-success" data-action="downloadInvoices">
                    <i class="icon-download"></i> Загрузить накладную</a>
            </div>
        </div>

        <div id="data-invoice"></div>

    </div>


    <div class="block" id="invoice-line-page">

        <div class="form-actions">
            <a href="javascript:void(0);" class="btn" data-action="back">
                <i class="icon-circle-arrow-left"></i> Назад</a>
        </div>

        <div id="data-invoice-line"></div>

    </div>

    <div class="block" id="location-map-page">

        <div class="form-actions">
            <a href="javascript:void(0);" class="btn" data-action="back">
                <i class="icon-circle-arrow-left"></i> Назад</a>
    
            <div class="pull-right">
                <a href="javascript:void(0);" class="btn btn-primary" data-action="saveLocationMap">
                    Сохранить</a>
            </div>
        </div>

        <div id="data-location-map"></div>

    </div>

    <div class="block" id="item-map-page">

        <div class="form-actions">
            <a href="javascript:void(0);" class="btn" data-action="back">
                <i class="icon-circle-arrow-left"></i> Назад</a>
    
            <div class="pull-right">
                <a href="javascript:void(0);" class="btn btn-primary" data-action="saveItemMap">
                    Сохранить</a>
            </div>
        </div>

        <div id="data-item-map"></div>

    </div>

</div>


<script type="text/javascript">

    $(function () {

        var view_StartPage = Backbone.View.extend({
            el: $("#start-page"),

            render: function () {
                this.refreshInvoiceTable();
            },

            events: {
                "click .btn[data-action='refreshInvoiceTable']": "refreshInvoiceTable",
                "click .btn[data-action='toggleSearchBlock']": "toggleSearchBlock",
                "click .btn[data-action='downloadInvoices']": "downloadInvoices",
                "click table tbody tr": "goToInvoicePage",
                "keyup.typeahead input[name='LOCATION_NAME']": "locationTypeahead",
                "keyup.typeahead input[name='CUSTOMER_NAME']": "supplierTypeahead"
            },

            goToInvoicePage: function (event) {

                if (event.target.type == "checkbox")
                    return;

                if ($(event.target).attr("data-type") == "noclick")
                    return;

                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/invoice/" + id, true);
            },

            toggleSearchBlock: function () {
                $("#invoiceSearchBlock").toggle();
            },

            downloadInvoices: function () {

                var ids = [];
                var path = "";

                $("input[name='SELECTED_GUID_RECORD']:checked").each(function (i) {
                    ids.push[$(this).val()];
                    path += "GUID_RECORD=" + $(this).val() + "&"
                });

                document.location = "/document/download/?" + path;
            },

            refreshInvoiceTable: function (el) {
                var local_el = this.el;
                $("#error-page").hide();

                $.get("/document/IncomingInvoices/",
                    $("form[name='INVOICES-FILTER']").serialize(),
                    function (data) {
                        $("#data-table").html(data);
                        $(local_el).show();
                        $(".tablesorter").tablesorter();
                    }).error(function (data) {
                        var response = $.parseJSON(data.responseText);
                        $("#error-page").html(response.message);
                        $("#error-page").show();
                    });
            },

            locationTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {

                        if (query == "") {
                            $("input[name='LOCATION_GUID']").val("");
                            return;
                        }

                        return $.get('/location/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='LOCATION_GUID']").val(obj.id);
                    }
                });
            },

            supplierTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {

                        if (query == "") {
                            $("input[name='CUSTOMER_GUID']").val("");
                            return;
                        }

                        return $.get('/supplier/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='CUSTOMER_GUID']").val(obj.id);
                    }
                });
            }


        });


        var view_InvoicePage = Backbone.View.extend({
            el: $("#invoice-page"),
            index: undefined,

            render: function (id) {
                this.index = id;
                this.loadInvoice(id);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='downloadInvoices']": "downloadInvoices",
                "click table tbody tr": "goToInvoiceLinePage",
                "click .btn[data-action='setLocationMapping']": "setLocationMapping"
            },

            back: function () {
                window.history.back();
            },

            goToInvoiceLinePage: function (event) {
                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/invoice/" + this.index + "/" + id, true);
            },

            downloadInvoices: function (event) {
                document.location = "/document/download/?GUID_RECORD=" + this.index;
            },

            loadInvoice: function (id) {
                var local_el = this.el;

                $.get('/document/IncomingInvoice/' + id, function (data) {
                    $("#data-invoice").html(data);
                    $(local_el).show();
                    $(".tablesorter").tablesorter({
                        headers: {
                            0: { sorter: 'digit' } // column number, type
                        }
                    });
                });
            },

            setLocationMapping: function (event) {
                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/locationmap/" + this.index, true);
            }

        });


        var view_InvoiceLinePage = Backbone.View.extend({
            el: $("#invoice-line-page"),
            index: undefined,
            parentId: undefined,

            render: function (id_parent, id) {

                this.index = id;
                this.parentId = id_parent;

                this.loadInvoiceLine(id);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='setItemMapping']": "setItemMapping"
            },

            back: function () {
                window.history.back();
            },

            loadInvoiceLine: function (id) {
                var local_el = this.el;
                $.get('/document/IncomingInvoiceLine/' + id, function (data) {
                    $("#data-invoice-line").html(data);
                    $(local_el).show();
                });
            },

            setItemMapping: function (event) {
                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/productmap/" + this.index, true);
            }

        });


        var view_ItemMapPage = Backbone.View.extend({
            el: $("#item-map-page"),
            index: undefined,

            render: function (id) {

                this.index = id;
                this.loadItemMap(id);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='saveItemMap']": "saveItemMap",
                "keyup.typeahead input[name='ITEM_NAME']": "itemTypeahead"
            },

            back: function () {
                window.history.back();
            },

            loadItemMap: function (id) {
                var local_el = this.el;

                $.get('/product/MapDetailsByInvoiceLineEdit/' + id, function (data) {
                    $("#data-item-map").html(data);
                    $(local_el).show();
                });
            },

            saveItemMap: function () {
                $.ajax({
                    type: 'POST',
                    url: '/product/MapDetailsSave/',
                    data: {
                        ITEM_GUID: $("form[name='ITEMS_MAPPING'] input[name='MAP_ITEM_GUID']").val(),
                        SUPPLIER_ITEM_GUID: $("form[name='ITEMS_MAPPING'] input[name='ITEM_GUID']").val()
                    },
                    success: function () {
                        window.history.back();
                    }
                });
            },

            itemTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {
                        return $.get('/product/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='MAP_ITEM_GUID']").val(obj.id);
                    }
                });
            }

        });

        var view_LocationMapPage = Backbone.View.extend({
            el: $("#location-map-page"),
            index: undefined,

            render: function (id) {

                this.index = id;
                this.loadLocationMap(id);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='saveLocationMap']": "saveLocationMap",
                "keyup.typeahead input[name='LOCATION_NAME']": "locationTypeahead"
            },

            back: function () {
                window.history.back();
            },

            loadLocationMap: function (id) {
                var local_el = this.el;
                $.get('/location/MapDetailsByInvoiceLineEdit/' + id, function (data) {
                    $("#data-location-map").html(data);
                    $(local_el).show();
                });
            },

            saveLocationMap: function () {
                $.ajax({
                    type: 'POST',
                    url: '/location/MapDetailsSave/',
                    data: $("form[name='LOCATIONS_MAPPING']").serialize(),
                    success: function () {
                        window.history.back();
                    }
                });
            },

            locationTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {
                        return $.get('/location/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='RIGHT_LOCATION_GUID']").val(obj.id);
                    }
                });
            }

        });


        var Views = {
            startPage: new view_StartPage(),
            invoicePage: new view_InvoicePage(),
            invoiceLinePage: new view_InvoiceLinePage(),
            itemMapPage: new view_ItemMapPage(),
            locationMapPage: new view_LocationMapPage()
        };


        var Controller = Backbone.Router.extend({
            routes: {
                "": "start", // Пустой hash-тэг
                "!/": "start", // Начальная страница
                "!/invoice/:id": "showInvoice",                  // Блок просмотра накладной
                "!/invoice/:id_parent/:id": "showInvoiceLine",    // Блок просмотра позиции
                "!/productmap/:id": "editProductMap",
                "!/locationmap/:id": "editLocationMap"
            },

            initialize: function (options) {
            },

            start: function () {
                $(".block").hide();

                if (Views.startPage != null) {
                    Views.startPage.render();
                }
            },

            showInvoice: function (id) {
                $(".block").hide();

                if (Views.invoicePage != null) {
                    Views.invoicePage.render(id);
                }
            },

            showInvoiceLine: function (id_parent, id) {
                $(".block").hide();

                if (Views.invoiceLinePage != null) {
                    Views.invoiceLinePage.render(id_parent, id);
                }
            },

            editProductMap: function (id) {
                $(".block").hide();

                if (Views.itemMapPage != null) {
                    Views.itemMapPage.render(id);
                }
            },

            editLocationMap: function (id) {
                $(".block").hide();

                if (Views.locationMapPage != null) {
                    Views.locationMapPage.render(id);
                }
            }

        });

        var controller = new Controller(); // Создаём контроллер
        Backbone.history.start();  // Запускаем HTML5 History push 

    })

</script>